package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
//拦截器  =>  抽取从request中token的代码
public class JwtInterceptor  extends HandlerInterceptorAdapter{
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    //在controller方法执行前,先执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获得Authorization的头内容(token)
        String authorizationHeader = request.getHeader("Authorization");
        //2.判断是否存在该请求头
        if (!StringUtils.isEmpty(authorizationHeader) && authorizationHeader.startsWith("Bearer ")) {
            //3.截掉"Bearer "部分 解析token
            String token = authorizationHeader.substring(7);
            Claims claims = jwtUtil.parserToken(token);

            //解析出用户信息
            if (claims != null) {
                //将用户信息放入request域中
                String role = (String) claims.get("role");

                //claims_admin管理员   claims_user普通用户
                request.setAttribute("claims_"+role,claims);

                System.out.println("将Jwt载荷信息放入到request域中"+"claims_"+role);
            }
        }

        //放行
        return true;

    }
}